/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mrroman.linksender.gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.ResourceBundle;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import com.mrroman.linksender.Configuration;
import com.mrroman.linksender.ioc.In;
import com.mrroman.linksender.ioc.Init;
import com.mrroman.linksender.ioc.Locales;
import com.mrroman.linksender.ioc.Name;
import com.mrroman.linksender.ioc.Prototype;
import com.mrroman.linksender.sender.Message;
import com.mrroman.linksender.sender.MessagePoint;
import com.mrroman.linksender.sender.PrivateMessagePoint;

/**
 *
 * @author gorladam
 */
@Name("gui.MessageDialog")
@Prototype
public class MessageDialog extends JFrame implements ActionListener {

    @Locales
    private ResourceBundle messages;
    @In
    private MessagePoint msgPoint;
    @In
    private PrivateMessagePoint privPoint;
    @In
    private Configuration config;
    @In
    private PingListener pingListener;
    private Object[] listOfUsers;
    private JTextArea textArea;
    private JList list;

    @Init
    public void init() {
        this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        this.setTitle(messages.getString("send_message_dialog"));
        JPanel main = new JPanel(new BorderLayout());
        this.setLayout(new BorderLayout());
        this.add(main);
        //this.setModal(false);

        //List of users
        ArrayList<String> aList = pingListener.getActiveUsers();
        aList.add(0, messages.getString("send_message_dialog_all"));
        listOfUsers = aList.toArray();

        //Create and initialize the buttons.
        final JButton cancelButton = new JButton(messages.getString("cancel"));
        cancelButton.addActionListener(this);
        //
        final JButton okButton = new JButton(messages.getString("ok"));
        okButton.setActionCommand("ok");
        okButton.addActionListener(this);
        getRootPane().setDefaultButton(okButton);

        //main part of the dialog
        list = new JList(listOfUsers);
        list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        list.setSelectedIndex(0);
        JScrollPane listScroller = new JScrollPane(list);
        listScroller.setPreferredSize(new Dimension(250, 80));
        listScroller.setAlignmentX(LEFT_ALIGNMENT);

        //Create a container so that we can add a title around
        //the scroll pane.  Can't add a title directly to the
        //scroll pane because its background would be white.
        //Lay out the label and scroll pane from top to bottom.
        JPanel listPane = new JPanel();
        listPane.setLayout(new BoxLayout(listPane, BoxLayout.PAGE_AXIS));
        JLabel label = new JLabel(messages.getString("send_message_dialog"));
        label.setLabelFor(list);
        listPane.add(label);
        listPane.add(Box.createRigidArea(new Dimension(0, 5)));
        listPane.add(listScroller);
        listPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        list.setFocusable(false);
        list.addListSelectionListener(new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent e) {
                ListSelectionModel lsm = (ListSelectionModel) ((JList) e.getSource()).getSelectionModel();
                if (lsm.isSelectionEmpty()) {
                    cancelButton.setEnabled(true);
                    okButton.setEnabled(!true);
                } else {
                    cancelButton.setEnabled(true);
                    okButton.setEnabled(true);
                    if (lsm.isSelectedIndex(0)) {
                        ((JList) e.getSource()).setSelectedIndex(0);
                    }
                }
//                textArea.requestFocus();
            }
        });
//        list.addMouseListener(new MouseAdapter() {
//
//            @Override
//            public void mouseReleased(MouseEvent e) {
//                super.mouseReleased(e);
//                textArea.requestFocus();
//            }
//        });

        //Text pane
        JPanel textPane = new JPanel();
        textPane.setLayout(new BorderLayout());
        textPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
        textArea = new JTextArea();
        textArea.setFont(textPane.getFont());
        textArea.setWrapStyleWord(true);

        textArea.addKeyListener(new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    if (e.getModifiers() == 0) {
                        actionPerformed(new ActionEvent(this, 0, "ok"));
                    } else {
                        textArea.replaceRange("\n",
                                textArea.getSelectionStart(),
                                textArea.getSelectionEnd());
                    }
                }
            }
        });

        JScrollPane textScroller = new JScrollPane(textArea);
        textScroller.setPreferredSize(new Dimension(150, 80));
        textPane.add(textScroller);

        //Lay out the buttons from left to right.
        JPanel buttonPane = new JPanel();
        buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
        buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
        buttonPane.add(Box.createHorizontalGlue());
        buttonPane.add(cancelButton);
        buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
        buttonPane.add(okButton);

        //Put everything together, using the content pane's BorderLayout.
        JPanel listAndTextPane = new JPanel(new BorderLayout());
        listAndTextPane.add(listPane, BorderLayout.CENTER);
        listAndTextPane.add(textPane, BorderLayout.PAGE_END);
        main.add(listAndTextPane, BorderLayout.CENTER);
        main.add(buttonPane, BorderLayout.PAGE_END);

        //Initialize values.
        //setValue(initialValue);
        pack();
        setLocationRelativeTo(null);
        this.addWindowFocusListener(new WindowFocusListener() {

            @Override
            public void windowGainedFocus(WindowEvent e) {
                textArea.requestFocus();
            }

            @Override
            public void windowLostFocus(WindowEvent e) {
            }
        });
    }

    public void setSelectedUsers(String... preselectedUsers) {
        list.setSelectedIndex(-1);
        for (String pre : preselectedUsers) {
            for (int i = 0; i < listOfUsers.length; i++) {
                Object k = listOfUsers[i];
                if (pre.equals(k)) {
                    list.setSelectedValue(k, true);
                }
            }
        }
    }

    //Handle clicks on the Set and Cancel buttons.
    @Override
    public void actionPerformed(ActionEvent e) {
        if ("ok".equals(e.getActionCommand())) {
            String text = textArea.getText();
            Message preparedMessage = new Message(config.getNick(), text);
            for (Object oUser : list.getSelectedValues()) {
                String sUser = (String) oUser;
                InetAddress ipUser = pingListener.getAddressOfUser(sUser);
                if (ipUser != null) {
                    privPoint.sendMessage(preparedMessage, ipUser);
                } else if (messages.getString("send_message_dialog_all").equals(sUser)) {
                    msgPoint.sendMessage(preparedMessage);
                    break;
                }
            }
        }
        setVisible(false);
    }
}
